<template>
  <div class="dataTarget">
    <el-divider content-position="left">
      <i></i>数据来源
    </el-divider>

    <el-form ref="form" :model="dataTarget" label-width="120px" :rules="formRules">
      <el-form-item label="数据库类型" prop="databaseType">
        <el-select v-model="dataTarget.databaseType" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseTypeEvent()">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="database">
        <el-select v-model="dataTarget.database" clearable filterable placeholder="请选择" style="width: 220px" @change="chooseDatabaseEvent()">
          <el-option v-for="item in databaseOptions" :key="item.id" :label="item.datasourceName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <el-divider content-position="left">
      <i></i>数据库表
    </el-divider>
    <div class="tableBox">
      <znxd-list-modify v-model="dataTarget.writeToDataSources" :formColumn="formColumn" :initData="tableData"></znxd-list-modify>
    </div>

    <el-dialog title="选择" :visible.sync="linkVisible " append-to-body width="80%">
      <el-scrollbar wrapClass="scrollbar-wrapper">
        <column-link-setting ref="fromColumnLink" v-model="currentMappingFileds" :initData="readAndWriteData"></column-link-setting>
      </el-scrollbar>
    </el-dialog>

    <el-dialog title="设置" :visible.sync="updateVisible" append-to-body width="600px">
      <el-scrollbar wrapClass="scrollbar-wrapper">
        <znxd-form v-if="updateVisible" v-model="dataTarget.writeToDataSources[indexUpdate]" labelWidth="200px" :formColumn="formColumnUpdate" :initData="initDataUpdate"></znxd-form>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>
<script>
import { deepCopy } from "@/utils/data.js";
import { typeGetDataSource } from "@/api/dataset/database.js";
import { getTables, getColumnsType } from "@/api/dataset/table.js";
import columnLinkSetting from "./columnLink";
import { selectDictionaryByType } from "@/api/dict";

export default {
  components: { columnLinkSetting },
  data() {
    return {
      formRules: {
        databaseType: [{ required: true, message: "不能为空" }],
        database: [{ required: true, message: "不能为空" }]
      },
      dataTarget: {
        databaseType: null,
        database: null,
        writeToDataSources: []
      },
      // 数据库类型字典
      typeOptions: [
        // {
        //   label: "mysql",
        //   value: "mysql"
        // },
        // {
        //   label: "oracle",
        //   value: "oracle"
        // },
        // {
        //   label: "sqlserver",
        //   value: "sqlserver"
        // },
        // {
        //   label: "postgresql",
        //   value: "postgresql"
        // },
        // {
        //   label: "dm",
        //   value: "dm"
        // }
      ],
      updateWayOptions: [
        {
          label: "数据追加",
          value: 0
        },
        {
          label: "数据覆盖",
          value: 1
        },
        {
          label: "增量更新",
          value: 2
        }
      ],
      buildTableWayOptions: [
        {
          label: "选择已有数据表",
          value: 0
        },
        {
          label: "自动创建数据表",
          value: 1
        }
      ],
      databaseOptions: [],
      tableOptions: [], // 表数据
      tableSourceData: [], // 表下拉选择数据（标准模板数据）
      // 数据库表字段
      formColumn: [
        // {
        //   name: "writerDataSourceName",
        //   label: "接口源",
        //   type: "label"
        // },
        // {
        //   name: "tableName",
        //   label: "目标数据表",
        //   type: "select",
        //   options: this.tableOptions
        // },
        // {
        //   init: "自动创建",
        //   label: "目标表建立方式",
        //   type: "select",
        //   options: this.buildTableWayOptions
        // },
        // {
        //   name: "updateWay",
        //   label: "更新方式",
        //   type: "select",
        //   options: this.updateWayOptions
        // }
      ],
      tableData: [], // 数据库表数据
      currentColumnData: [], // 当前目标表字段
      currentMappingFileds: [], // 当前字段链接关系
      readAndWriteData: [], // 当前字段读写数据
      linkVisible: false, // 字段映射弹出框
      updateVisible: false, // 增量更新设置
      formColumnUpdate: [],
      indexUpdate: 0,
      initDataUpdate: {}
    };
  },
  props: {
    initData: Object,
    mode: String,
    dataSource: Array
  },
  watch: {
    dataTarget: {
      deep: true,
      handler: function (val) {
        console.log("dataTarget", val);
        this.$emit("input", val);
      }
    },
    initData: {
      deep: true,
      handler: function (val) {
        // this.$refs.form.resetFields();

        this.dataTarget.databaseType = val.writerDatabaseType;
        this.dataTarget.database = val.writerDataSourceId;
        this.dataTarget.writeToDataSources = val.writeToDataSources;
        // this.tableData = val.writeToDataSources || [];
        // this.tableData = [];
        this.tableData = deepCopy(val.writeToDataSources)

        this.chooseTypeEvent();
        this.chooseDatabaseEvent();
        let _this = this;
        setTimeout(function () {
          _this.$refs.form.clearValidate();// 消除校验,这里的setTimeOut不能去掉,去掉之后会不生效
        }, 30);
      }
    },
    dataSource: {
      deep: true,
      handler: function (val) {
        console.log("dataSource", val);
        // this.$refs.form.resetFields();

        if (val) {
          let arrData = [...this.dataTarget.writeToDataSources];
          // console.log("arrData 1", arrData);
          val.map(x => {
            // console.log("x", x)
            // 增量更新
            let filters = arrData.filter(d => { return d.datasourceId.toString() === x.id.toString() });
            if (filters.length === 0) {
              let obj = {
                datasourceId: x.id,
                datasourceName: x.datasourceName,
                redadColumns: x.interfaceResults || [],
                requestParams: x.requestParams,
                isCreateTable: 1,
                updateWay: 0
              }
              // console.log("obj", obj)
              arrData.push(obj);
            } else {
              arrData.forEach((d, index) => {
                if (d.datasourceId.toString() === x.id.toString()) {
                  let obj = {
                    ...d,
                    // redadColumns: x.interfaceResults || []
                    datasourceId: x.id,
                    datasourceName: x.datasourceName,
                    redadColumns: x.interfaceResults || [],
                    requestParams: x.requestParams
                  }
                  // console.log("obj2", obj)
                  arrData[index] = obj;
                }
              })
            }
          })

          // console.log(" this.tableData", this.tableData);
          // 删除数据源
          arrData.map((d, index) => {
            let filters = val.filter(x => { return d.datasourceId.toString() === x.id.toString() });
            if (filters.length === 0) {
              arrData.splice(index, 1);
            }
          })
          this.tableData = arrData;
        }
      }
    },
    tableOptions(val) {
      let arrData = [];
      val.map((x) => {
        let obj = {
          ...x,
          label: x.tableName,
          key: x.tableName,
          value: x.tableName
        };
        arrData.push(obj);
      });
      this.tableSourceData = arrData;
      // console.log(this.tableSourceData);
      this.initFormColumn();
    },
    currentMappingFileds(val) {
      let _this = this;
      _this.dataTarget.writeToDataSources.forEach(x => {
        if (x.datasourceId === this.readAndWriteData.datasourceId) {
          _this.$set(x, "mappingFileds", val)
        }
      })
    }
  },
  methods: {
    initFormColumn() {
      let _this = this;
      let _formColumn = [{
        name: "datasourceName",
        label: "接口源",
        type: "label"
      },
      {
        name: "isCreateTable",
        label: "目标表建立方式",
        type: "select",
        options: this.buildTableWayOptions
      },
      {
        name: "writerTable",
        label: "目标数据表",
        type: "selectOrInput",
        options: this.tableSourceData,
        handleGetType: function (row) {
          return row.isCreateTable === 0 ? "select" : "input";
        },
        handleChange: function (row) {
          _this.chooseTableEvent(row);
        }
      },
      {
        label: "字段映射",
        type: "buttons",
        buttons: [
          {
            label: "字段映射",
            type: "success",
            plain: true,
            size: "mini",
            handelClick: (row) => {
              _this.setLinkEvent(row);
            },
            handleGetVisible: function (row) {
              return row.isCreateTable === 0;
            }
          }
        ]
      },
      {
        name: "updateWay",
        label: "更新方式",
        type: "select",
        options: this.updateWayOptions
        // handleChange: function (row) {
        //   console.log("handleChange row ", row)
        //   // _this.initFormColumn();
        // }
      },
      {
        label: "增量更新设置",
        type: "buttons",
        buttons: [
          {
            label: "增量更新设置",
            type: "success",
            plain: true,
            size: "mini",
            handelClick: (row, index) => {
              _this.setUpdateEvent(row, index);
            },
            handleGetVisible: function (row) {
              return row.updateWay === 2;
            }
          }
        ]
      }
        // {
        //   name: "startTimeParamName",
        //   label: "增量更新开始时间",
        //   type: "select",
        //   multiple: false,
        //   getOptions: function getOptions(row) {
        //     // console.log("getOptions row", row);
        //     let _options = [];
        //     // console.log("row.redadColumns", row.redadColumns);
        //     if (row.requestParams) {
        //       row.requestParams.map(x => {
        //         let obj = {
        //           label: x.paramName,
        //           value: x.paramName
        //         }
        //         _options.push(obj);
        //       })
        //     }
        //     // console.log("_options", _options);
        //     return _options;
        //   },
        //   handleGetVisible: function (row) {
        //     return row.updateWay === 2;
        //   }
        // },
        // {
        //   name: "endTimeParamName",
        //   label: "增量更新结束时间",
        //   type: "select",
        //   multiple: false,
        //   getOptions: function getOptions(row) {
        //     // console.log("getOptions row", row);
        //     let _options = [];
        //     // console.log("row.redadColumns", row.redadColumns);
        //     if (row.requestParams) {
        //       row.requestParams.map(x => {
        //         let obj = {
        //           label: x.paramName,
        //           value: x.paramName
        //         }
        //         _options.push(obj);
        //       })
        //     }
        //     // console.log("_options", _options);
        //     return _options;
        //   },
        //   handleGetVisible: function (row) {
        //     return row.updateWay === 2;
        //   }
        // }
      ]

      this.$set(this, "formColumn", _formColumn);
    },
    chooseTypeEvent() {
      if (!this.dataTarget.databaseType) { return }
      let obj = {
        tableType: this.dataTarget.databaseType
      };
      typeGetDataSource(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.databaseOptions = data.content;
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    chooseDatabaseEvent() {
      if (!this.dataTarget.database) { return }
      let obj = {
        datasourceId: this.dataTarget.database
      };
      getTables(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.tableOptions = data.content;
          // if (isFirst) {
          //   this.tablesData = [];
          // }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    // 校验数据
    validateForm() {
      let flag = true;
      // switch (this.mode) {
      //   default:
      //     break;
      // }
      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });

      // this.dataTarget.writeToDataSources
      if (!this.dataTarget.writeToDataSources || this.dataTarget.writeToDataSources.length === 0) {
        flag = false;
        this.$message({
          message: "数据库表不能为空",
          type: "error"
        });
        return flag;
      }

      console.log("this.dataTarget.writeToDataSources", this.dataTarget.writeToDataSources);
      let filter = this.dataTarget.writeToDataSources.filter(x => {
        // writerTable
        console.log("x.writerTable", x.writerTable);
        return (!x.writerTable || x.writerTable === "")
      })

      console.log("filter", filter);

      if (filter && filter.length > 0) {
        flag = false;
        this.$message({
          message: "目标数据表不能为空",
          type: "error"
        });
        return flag;
      }

      return flag;
    },
    chooseTableEvent(row) {
      let _this = this;
      let obj = {
        datasourceId: this.dataTarget.database,
        tableName: row.writerTable
      };
      getColumnsType(obj).then((res) => {
        let data = res.data;
        if (data.code === 200) {
          this.currentColumnData = data.content;
          _this.dataTarget.writeToDataSources.forEach(x => {
            if (x.datasourceId === row.datasourceId) {
              _this.$set(x, "writerColumns", data.content)
            }
          })
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          });
        }
      });
    },
    setLinkEvent(row) {
      console.log("row", row);
      this.readAndWriteData = row;
      this.linkVisible = true;
    },
    setUpdateEvent(row, index) {
      this.indexUpdate = index;
      this.updateVisible = true;
      this.initDataUpdate = row;

      let _options = [];
      if (row.requestParams) {
        row.requestParams.map(x => {
          let obj = {
            label: x.paramName,
            value: x.paramName
          }
          _options.push(obj);
        })
      }
      this.formColumnUpdate = [
        {
          name: "startTimeParamName",
          label: "增量更新开始时间",
          type: "select",
          multiple: false,
          options: _options
        },
        {
          name: "endTimeParamName",
          label: "增量更新结束时间",
          type: "select",
          multiple: false,
          options: _options
        }
      ]
    },
    // import { selectDictionaryByType } from "@/api/dict";
    getDBType() {
      selectDictionaryByType({ type: "dbType" })
        .then((res) => {
          let data = res.data;
          if (data.code === 200) {
            let options = [];
            data.data.map((x) => {
              options.push({ label: x.value, value: x.value });
            });
            this.typeOptions = options;
            // this.initFormColumn();
          } else {
            // this.$message.error(data.msg);
          }
        })
        .catch(() => {
          // this.$message.error("操作失败");
        });
    }
    // setRules() {
    //   this.formRules = {
    //     databaseType: [{ required: true, message: "不能为空" }],
    //     database: [{ required: true, message: "不能为空" }]
    //   }
    // }
  },
  mounted() {
    this.getDBType();
    this.initFormColumn();
    // if (this.initData.writerColumns) { this.initSelection = [...this.initData.writerColumns]; }
    // this.setRules();
  }
};
</script>
<style lang="scss" scoped>
.dataTarget {
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
}
</style>
